package com.starters.redisson.config;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

/**
 * TODO: redisson 分布式锁
 *
 * @author wuyijie
 * @date 2022/2/13 12:25 AM
 */
public class RedissonDistributedLocker implements IDistributedLocker{
    private final RedissonClient redissonClient;
    private final CustomizedRedissonProperties redissonProperties;

    public RedissonDistributedLocker(RedissonClient redissonClient, CustomizedRedissonProperties redissonProperties) {
        this.redissonClient = redissonClient;
        this.redissonProperties = redissonProperties;
    }

    @Override
    public void lock(String key) {
        RLock rLock = redissonClient.getLock(key);
        rLock.lock(redissonProperties.getTimeout(), TimeUnit.MILLISECONDS);
    }

    @Override
    public void tryLock(String key) throws InterruptedException {
        RLock rLock = redissonClient.getLock(key);
        rLock.tryLock(redissonProperties.getTryTimeout(),redissonProperties.getTimeout(), TimeUnit.MILLISECONDS);
    }

    @Override
    public void lock(String key, int timeout, TimeUnit timeUnit) {
        RLock rLock = redissonClient.getLock(key);
        rLock.lock(timeout, timeUnit);
    }

    @Override
    public void unLock(String key) {
        RLock rLock = redissonClient.getLock(key);
        rLock.unlock();

    }
}
